const fs = require('fs');
const path = require('path');

let fileChanged = false;

module.exports = {
  // 读取json文件内容
  getJsonFile(filePath) {
    let json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8');
    return JSON.parse(json);
  },
  // 读取文件夹下左右文件
  getDirFiles(dir) {
    let jsonFileNames = [];
    let filenames = fs.readdirSync(path.resolve(__dirname, dir));
    if (filenames) {
      filenames.forEach(filename => {
        let f = filename.match(/^([\w\W]+?)\.json$/);
        if (f && f.length > 1) jsonFileNames.push(f[1]);
      })
    }
    return jsonFileNames;
  },
  // 监听文件夹
  watchDir(dir, callback) {
    fs.watch(path.resolve(__dirname, dir), (etype, filename) => {
      if (filename && etype === 'rename' && /^([\w\W]+?)\.json$/.test(filename)) {
        if (typeof callback === 'function') {
          callback(RegExp.$1);
        }
      }
    })
  }
}